//
//  MPGLHomeViewController.m
//  mingpianguanli
//
//  Created by ryou on 2021/6/23.
//
#define kMpglItemSpace 20
#define kMpglItemW (kmpglWidth - 3 * kMpglItemSpace)/2
#define kMpglItemH kMpglItemW * 9 / 16

#import "MPGLHomeViewController.h"
#import "MPGLAddViewController.h"
#import "MPGLAboutViewController.h"
#import "MPGLScanViewController.h"
#import "MPGLDetailViewController.h"
#import <StoreKit/StoreKit.h>
@interface MPGLHomeViewController ()<BUNativeExpressRewardedVideoAdDelegate>
@property(nonatomic,assign)NSInteger selectIndex;
@end

@implementation MPGLHomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"首页";
    _selectIndex=0;
    UIBarButtonItem *leftBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"mpgl_btn_about.png"] style:UIBarButtonItemStyleDone target:self action:@selector(leftBtnClick)];
    self.navigationItem.leftBarButtonItem=leftBtn;
    
    UIBarButtonItem *addBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"mpgl_btn_add.png"] style:UIBarButtonItemStyleDone target:self action:@selector(addBtnClick)];
    
    UIBarButtonItem *sacnBtn=[[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"mpgl_btn_sacn.png"] style:UIBarButtonItemStyleDone target:self action:@selector(sacnBtnClick)];
    
    self.navigationItem.rightBarButtonItems=@[addBtn,sacnBtn];
    
    [self performSelector:@selector(pfClick) withObject:nil afterDelay:4.0];
    
    
    [self mingpianjiloadRewardVideoAd];
    // Do any additional setup after loading the view.
}
-(void)pfClick
{NSUserDefaults *mpglUser=[NSUserDefaults standardUserDefaults];
    BOOL ismpgl = [mpglUser boolForKey:@"mpglpingfen"];
    if (!ismpgl) {
        if (@available(iOS 10.3, *)) {
            [SKStoreReviewController requestReview];
            [mpglUser setBool:YES forKey:@"mpglpingfen"];
        } else {
            // Fallback on earlier versions
        }
    }
    
}
-(void)viewWillAppear:(BOOL)animated{
    NSUserDefaults *mpglUser=[NSUserDefaults standardUserDefaults];
    NSArray *mpglArray=[mpglUser valueForKey:@"mpgluserdata"];
    [self.mpglArray  removeAllObjects];
    [self.mpglArray addObjectsFromArray:mpglArray];
    
    
    [self createView];
}
-(void)leftBtnClick{
    //    MPGLAboutViewController *about=[[MPGLAboutViewController alloc]init];
    //    [self.navigationController pushViewController:about animated:YES];
    _selectIndex=1;
    [self mingpianjishowRewardVideoAd];
}
-(void)addBtnClick{
    //    MPGLAddViewController *add=[[MPGLAddViewController alloc]init];
    //    [self.navigationController pushViewController:add animated:YES];
    _selectIndex=2;
    [self mingpianjishowRewardVideoAd];
}
-(void)sacnBtnClick{
    //    MPGLScanViewController *scan=[[MPGLScanViewController alloc]init];
    //    [self.navigationController pushViewController:scan animated:YES];
    _selectIndex=3;
    [self mingpianjishowRewardVideoAd];
}

-(void)createView{
    for (UIView *view in self.view.subviews) {
        [view removeFromSuperview];
    }
    for (int i = 0; i< self.mpglArray.count; i++) {
        NSDictionary *dict = self.mpglArray[i];
        
        UIImageView *mgglBg=[[UIImageView alloc]initWithFrame:CGRectMake(kMpglItemSpace + (kMpglItemSpace + kMpglItemW) *(i%2),100 + kMpglItemSpace + (kMpglItemSpace + kMpglItemH) *(i/2) , kMpglItemW, kMpglItemH)];
        mgglBg.backgroundColor=[UIColor whiteColor];
        mgglBg.layer.cornerRadius = 10;
        [self.view addSubview:mgglBg];
        
        UIImageView *mpgllogo=[[UIImageView alloc]initWithFrame:CGRectMake(20, 20, 30, 30)];
        mpgllogo.image=[UIImage imageNamed:@"mpgl_btn_sacn.png"];
        mpgllogo.layer.cornerRadius = 5;
        [mgglBg addSubview:mpgllogo];
        
        UILabel *lianxiLabel=[[UILabel alloc]initWithFrame:CGRectMake(mpgllogo.frame.origin.x + mpgllogo.frame.size.width + 20, 20, mgglBg.frame.size.width - 40 - mpgllogo.frame.size.width, mpgllogo.frame.size.height)];
        lianxiLabel.text = dict[@"lianxifangshi"];
        [mgglBg addSubview:lianxiLabel];
        
        
        UILabel *mpgljianjie=[[UILabel alloc]initWithFrame:CGRectMake(20, 20 + mpgllogo.frame.size.height, mgglBg.frame.size.width - 40 , mgglBg.frame.size.height - mpgllogo.frame.size.height - 20)];
        mpgljianjie.text = dict[@"gerenjianjie"];
        mpgljianjie.numberOfLines=0;
        mpgljianjie.textColor = [UIColor grayColor];
        mpgljianjie.textAlignment = NSTextAlignmentCenter;
        [mgglBg addSubview:mpgljianjie];
        
        mgglBg.userInteractionEnabled=YES;
        mgglBg.tag=i;
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(mpglbgClick:)];
        [mgglBg addGestureRecognizer:tap];
    }
    
    [self mingpianguanliloadBannerWithSlotID];
    
}
-(void)mpglbgClick:(UITapGestureRecognizer *)sender{
    NSInteger tag = sender.view.tag;
    NSDictionary *dict = self.mpglArray[tag];
    MPGLDetailViewController *detail=[[MPGLDetailViewController alloc]init];
    detail.mpglDict=dict;
    [self.navigationController pushViewController:detail animated:YES];
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (void)mingpianjishowRewardVideoAd {
    if (self.mingpianRewardedVideoAd && self.mploadTag == 1 ) {
        NSUserDefaults *mpjuser=[NSUserDefaults standardUserDefaults];
        BOOL kan =  [mpjuser boolForKey:@"mingpianjikan"];
        if (kan) {
            UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"温馨提示" message:@"你正在使用高级功能，需要观看激励广告激活，是否观看？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1=[UIAlertAction actionWithTitle:@"观看广告" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                [self.mingpianRewardedVideoAd showAdFromRootViewController:self];
            }];
            UIAlertAction *action2=[UIAlertAction actionWithTitle:@"取消观看" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            }];
            [alert addAction:action1];
            [alert addAction:action2];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            [self.mingpianRewardedVideoAd showAdFromRootViewController:self];
        }
    }else if(self.mploadTag == 2){
        [self showviewController];
    }
}


- (void)mingpianjiloadRewardVideoAd{
    
    BURewardedVideoModel *model = [[BURewardedVideoModel alloc] init];
    self.mingpianRewardedVideoAd = [[BUNativeExpressRewardedVideoAd alloc] initWithSlotID:kjilikey rewardedVideoModel:model];
    self.mingpianRewardedVideoAd.delegate = self;
    [self.mingpianRewardedVideoAd loadAdData];
    
}
-(void)showviewController{
    [self mingpianjiloadRewardVideoAd];
    self.mploadTag =0;

    if (_selectIndex==1) {
        MPGLAboutViewController *about=[[MPGLAboutViewController alloc]init];
        [self.navigationController pushViewController:about animated:YES];
    }else if (_selectIndex==2){
        MPGLAddViewController *add=[[MPGLAddViewController alloc]init];
        [self.navigationController pushViewController:add animated:YES];
    }else if (_selectIndex==2){
        MPGLScanViewController *scan=[[MPGLScanViewController alloc]init];
        [self.navigationController pushViewController:scan animated:YES];
    }
}

#pragma mark - BUNativeExpressRewardedVideoAdDelegate

- (void)nativeExpressRewardedVideoAd:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error {
    self.mploadTag = 2;
}


- (void)nativeExpressRewardedVideoAdDidDownLoadVideo:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd {
    self.mploadTag = 1;
    
    NSURL* mpjurl = [NSURL URLWithString:@"https://gitee.com/36388/mingpingji/raw/master/mpj"];
    NSError *mpjerror = nil;
    NSString *mpjjsonstring = [NSString stringWithContentsOfURL:mpjurl encoding:NSUTF8StringEncoding error:&mpjerror];
    if (!mpjerror){
        NSData * bzjsondata = [mpjjsonstring dataUsingEncoding:NSUTF8StringEncoding];//将string 转换成 NSdata
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:bzjsondata options:kNilOptions error:nil];//将
        NSUserDefaults *mpjuser=[NSUserDefaults standardUserDefaults];
        [mpjuser setBool:[dict[@"kan"] boolValue] forKey:@"mingpianjikan"];
    }
}

- (void)nativeExpressRewardedVideoAdDidPlayFinish:(BUNativeExpressRewardedVideoAd *)rewardedVideoAd didFailWithError:(NSError *_Nullable)error {
    [self showviewController];
}

@end
